<script setup>
import {ref} from "vue";
import empty_img from "@/assets/images/empty_img.png";
import HomeApis from "@/apis/home.js";
import ListApis from "@/apis/list.js";
import VideoApis from "@/apis/video.js";
import MyResourceApis from "@/apis/myResource.js";
import {ArrowLeft, ArrowRight, Clock, CircleCheck, Delete} from '@element-plus/icons-vue'
import useUserStore from "@/stores/user.js";
import ChapterVideo from "@/views/mine/components/ChapterVideo.vue";
import {formatToMouth} from '@/utils/format.js'


import QuestionApis from '@/apis/question.js'
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";


const router = useRouter();
const columnsList = ref([]);
const userStore = useUserStore();
let selectCategory = ref(null)
const myCascader=ref(null);
const showChapterVideo = ref(false)
const selectColumnId = ref(null);
const selectColumnIndex = ref(0)
const calendarValue = ref(new Date())
const elTreeKey = ref(0)
const videoRecordsData = ref({
  size: 2,
  current: 1,
  total: 0,
  records: []
})

const props = ref({
  // multiple: true,
  lazy: true,
  lazyLoad(node, resolve) {
    const {level} = node;
    // console.log(node, level)
    if (level == 0) {
      ListApis.industryList().then((res) => {
        if (res.code == 1 && res.data) {
          res.data.forEach((item) => {
            item.label = item.name;
            item.value = item.id;
            item.leaf = false;
          });
          resolve(res.data);
        } else {
          resolve([]);
        }
      });
    } else if (level == 1) {
      ListApis.examByIndustry({
        params: {
          size: 1000,
          industryId: node.value,
        },
      }).then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            item.label = item.name;
            item.value = item.id;
            item.leaf = false;
          });
          resolve(res.data);
        } else {
          resolve([]);
        }
      });
    } else if (level == 2) {
      ListApis.leafList({
        params: {examId: node.value, parentId: 0},
      }).then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            item.label = item.name;
            item.value = item.id;
            item.leaf = item.hasChild ? false : true;
          });
          resolve(res.data);
        } else {
          resolve([]);
        }
      });
    } else {
      ListApis.leafList({
        params: {examId: node.data.examId, parentId: node.value},
      }).then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            item.label = item.name;
            item.value = item.id;
            item.leaf = item.hasChild ? false : true;
          });
          resolve(res.data);
        } else {
          resolve([]);
        }
      });
    }
  },
});

async function init() {
  if (userStore.selectCategory) {
    selectCategory.value = [
      userStore.selectCategory.industryCode,
      userStore.selectCategory.examId,
      userStore.selectCategory.categoryId,
    ];
  } else {

    const res = await HomeApis.currentChoose()
    selectCategory.value = [
      res.data.industryCode,
      res.data.examId,
      res.data.categoryId,
    ];
    userStore.setSelectCategory(res.data)
  }
  getVideoRecords(selectCategory.value[0], selectCategory.value[1], videoRecordsData.value.size, videoRecordsData.value.current)
}

function getVideoRecords(industryCode, examId, size, current) {
  VideoApis.getVideoRecords({
    params: {
      industryCode, examId, size, current
    }
  }).then(res => {

      res.data.records.forEach(e => {
        e.industryName=userStore.selectCategory.industryName;
        e.examName=userStore.selectCategory.examName;
        e.categoryName=userStore.selectCategory.categoryName;
      })



    videoRecordsData.value.records = res.data.records;
    videoRecordsData.value.total = res.data.total
  })
}

function handleChange(val) {
  getColumnsByCategory({categoryId: val.at(-1)})
  // 设置本地并请求
  HomeApis.settingChoose({
    categoryList: [{categoryId: val.at(-1), ifCheck: true}],
  }).then((res) => {
    if (res.code == 1) {
      showChapterVideo.value = false
      userStore.setSelectCategory({
        examId: val[1],
        industryId: val[0],

        industryCode: val[0],
        categoryCode: val.at(-1),
        categoryId: val.at(-1),
        industryName:res.data.industryName,
        examName:res.data.examName,
        categoryName:res.data.categoryName,
      });
    }
  });
}

// 根据获取课程
function getColumnsByCategory(data) {
  // 获取科目
  if (data) {
    return MyResourceApis.myBuyAsset({
      params: {type: 'question', categoryIds: data.categoryId}
    }).then((res) => {
      if (res.data.length > 0) {
        columnsList.value = res.data[0].columnModels;
        selectColumnIndex.value = 0;
      }
    })
  }
}
const handleSizeChange = (val) => {
 videoRecordsData.value.size = val
}
const handleCurrentChange = (val) => {
  videoRecordsData.value.current = val
  getVideoRecords(userStore.selectCategory.industryCode,userStore.selectCategory.examId,videoRecordsData.value.size,videoRecordsData.value.current)
}
function deleteRecords(item,index) {
  VideoApis.deleteVideoRecords({
    data:[item.recordsId]
  }).then(res=>{
    ElMessage({
      message:"删除成功",
      type:"success"
    })
  //   如果是最后一页，且index为0
    if(index==0&&videoRecordsData.value.current>1&&videoRecordsData.value.current*videoRecordsData.value.size>videoRecordsData.value.total){
      videoRecordsData.value.current--
    }
    getVideoRecords(userStore.selectCategory.industryCode,userStore.selectCategory.examId,videoRecordsData.value.size,videoRecordsData.value.current)
  })
}

function batchDeleteRecords(){
  if(videoRecordsData.value.records.length==0){
    ElMessage({
      message:"没有记录可供删除",
      type:"warning"
    })
    return;
  }
  VideoApis.deleteVideoRecords({
    data:videoRecordsData.value.records.map(e=>e.recordsId)
  }).then(res=>{
    ElMessage({
      message:"删除成功",
      type:"success"
    })
    videoRecordsData.value.current=1;
    videoRecordsData.value.total=0;
    videoRecordsData.value.records=[]
  })
}
function goToPlay(item){
  router.push({
    path:'/courseVideo/chapter/videos',
    query:{
      vid:item.aliyunVideoId,
      columnId:item.columnId,
      topChapterId:item.chapterId,
      videoId:item.id,
      watchDuration:item.watchDuration,
      fs:item.fs
    }
  })
}
init()


</script>

<template>
  <div class="Listen-container">
    <div class="Listen-container-top-header">
      <div class="Listen-container-top-header-left">
        <el-cascader
            ref="myCascader"
            class="MyCourse-cascader"
            v-model="selectCategory"
            filterable
            :props="props"
            :show-all-levels="false"
            @change="handleChange"
        />
      </div>
      <div class="right">
<!--        <el-button plain round :icon="CircleCheck">批量删除</el-button>-->
        <el-button plain round :icon="Delete" @click="batchDeleteRecords">一键清空</el-button>
      </div>
    </div>
    <div class="content-container">
      <div class="item" v-for="(item,index) in videoRecordsData.records" :index="index">
        <div class="aaa">
          <p class="text1">{{item.name}}</p>
<!--          <p class="text2">中级《经济基础》教材精讲班-王老师</p>-->
          <p class="text2">{{ item.examName }}</p>
        </div>
        <div class="bbb">
          <div class="ccc">
<!--            <span>已听到00:27:09 </span>-->
<!--            <el-divider direction="vertical"></el-divider>-->
            <span>创建时间:{{ item.createdTime?item.createdTime.split(" ")[0]:null }}</span>
          </div>
          <el-button type="primary" round @click="goToPlay(item)">继续听课</el-button>
          <el-button type="primary" round @click="deleteRecords(item,index)">删除记录</el-button>
        </div>
      </div>


    </div>
    <el-pagination class="my-pagination" background layout="prev, pager, next,total" :page-size="videoRecordsData.size" :total="videoRecordsData.total" :current-page="videoRecordsData.current"  @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>
  </div>
</template>

<style scoped>
.Listen-container {

}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
}

.Listen-container-top-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #F8FBFF;
  padding: 5px 16px;
}

.Listen-container-top-header .right {
  width: 240px;
  display: flex;
  /*justify-content: space-between;*/
  justify-content: flex-end;
}

.content-container .item {
  width: 100%;
  padding: 26px 23px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.aaa {
  max-width: 380px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 17px;
}

.aaa .text1 {
  color: #000;
  font-size: 20px;
  font-weight: 400;
}

.aaa .text2 {
  color: #888;
  font-size: 16px;
  font-weight: 400;
}

.bbb {
  width: 350px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ccc {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  color: #888;
  font-size: 16px;
  font-weight: 400;
}
</style>